package com.itheima.controller;

import com.itheima.pojo.Emp;
import com.itheima.pojo.Result;
import com.itheima.service.EmpService;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;

@RestController
@Slf4j
public class LoginController {
    @Autowired
    private EmpService empService;

    @Value("${jwt.secret}")
    private String secret;

    @PostMapping("/login")
    public Result login(@RequestBody Emp emp) {
        log.info("用户登录:{}", emp);
        //根据用户名和密码查询一个员工
        Emp e = empService.login(emp);
        if (e != null) {
            //生成token
            HashMap<String, Object> map = new HashMap<>();
            map.put("id", e.getId());
            map.put("username", e.getUsername());
            String token = Jwts.builder()
                    .setClaims(map)
                    .signWith(SignatureAlgorithm.HS256, secret.getBytes())
                    .setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 2))
                    .compact();
            log.info("登录成功，欢迎:{},token：{}", e.getUsername(), token);
            return Result.success(token);
        }
        return Result.error("用户名或密码错误");
    }
}
